<?php
/**
 * 定时把采集到的车主信息导入到车主表里
 * 导入规则：导入当天采集的数据，不排重手机号码，但该手机号码不能在业务流程中
 */
#error_reporting ( 0 );
date_default_timezone_set ( "Asia/Shanghai" );
set_time_limit ( 0 );
if (isset ( $_SERVER ['REQUEST_URI'] )) {
    die ( 'error' );
}
if (! defined ( 'API_ROOT_PATH' )) {
    define ( 'API_ROOT_PATH', dirname ( __FILE__ ) );
}

require_once (API_ROOT_PATH . '/../inc/Config.php');
require_once (API_ROOT_PATH . '/../inc/dblink.php');
require_once (API_ROOT_PATH . '/../inc/Mysql.php');

global $db;

$db = new Mysql ( MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE );

function  getNextSleepSecond() {
    $date1 = time();
    $date2 = date('Y-m-d H:i:00',strtotime('+1 hour',$date1));
    $date2 = strtotime($date2);
    $s = $date2-$date1;

    $date1 = date('Y-m-d H:i:s',$date1);
    $date2 = date('Y-m-d H:i:s',$date2);

    print_r("nexttime:".$date2."\n");
    return $s;
}

while ( true ) {

    $sql = "SELECT * FROM au_car_owner_co WHERE status=1 AND imported=0 AND UNIX_TIMESTAMP(comefrom_createtime)+1*24*3600>'".time()."' ORDER BY owner_co_id  LIMIT 1";
    $row = $db->fetchOne($sql);
    if(!$row){
        $sleeptimes = getNextSleepSecond();
        //print_r("sleep:".$sleeptimes."\n");
        //echo $sql."\n";
        sleep($sleeptimes);
        continue;
    }

    //检查有效
    if(!$row['phone']){
        $sql = "UPDATE `au_car_owner_co` SET status=0 WHERE owner_co_id='".$row['owner_co_id']."'";
        //echo $row['owner_co_id'].' '.$row['name']."没有电话号码\n";
        $db->query($sql);
        continue;
    }
    //有重复不要紧，只要是不在业务流程中的，可再入
    //检查是否在业务中
    //查 au_car_owner表 ，看是否有记录，若有记录看流程是否结束
    $owner = $db->fetchOne("SELECT owner_id,business_status FROM au_car_owner WHERE phone='".$row['phone']."' ORDER BY owner_id DESC limit 1");
    if($owner){
        //线索表->失败(允许添加此线索）不再看车源状态，直接去添加
        if(!in_array($owner['business_status'],array(3,6))){//线索成功,继续看车源状态
            //车源状态-》失败（允许添加此线索）
            $car_info = $db->fetchOne("SELECT car_status FROM au_cars WHERE owner_id='".$owner['owner_id']."'");
            if($car_info){//已生成车源，看车源状态
                if(!in_array($car_info['car_status'],array(2,8,9))){//车源状态未失败,不允许 再次添加此线索
                    $sql = "UPDATE `au_car_owner_co` SET imported=1 WHERE owner_co_id='".$row['owner_co_id']."'";
                    //echo "电话号码".$row['phone']."已存在于au_car_owner表\n";
                    //echo "车源状态未失败，不允许再次添加此线索\n";
                    $db->query($sql);
                    continue;
                }else{//车源状态失败
                    //允许再次添加此线索
                    //echo "允许再次添加此线索\n";
                }
            }else{//尚未生成车源，不允许添加此线索
                $sql = "UPDATE `au_car_owner_co` SET imported=1 WHERE owner_co_id='".$row['owner_co_id']."'";
                //echo "电话号码".$row['phone']."已存在于au_car_owner表\n";
                $db->query($sql);
                //echo "尚未生成车源，不允许添加此线索\n";
                continue;
            }
        }else{//线索失败
            //允许添加此线索
            //echo "允许再次添加此线索\n";
        }
    }
    //匹配网站用户
    $arr = $db->fetchOne("SELECT uid FROM au_user WHERE pwd_mobile='".$row['phone']."'");
    //入库数据
    $vals = array();
    $vals["uid"] = $arr['uid'];
    $vals["seller_name"] = $row['name'];
    $vals["phone"] = $row['phone'];
    $vals["car_model"] = $row['series'];
    $vals["brand_id"] = @$row['brand_id']?$row['brand_id']:0;
    $vals["series_id"] = @$row['series_id']?$row['series_id']:0;
    $vals["model_id"] = @$row['model_id']?$row['model_id']:0;
    $vals["mileage"] = $row['mileage'];
    $vals["first_reg_date"] = $row['register_at'];
    $vals["isou_id"] = $row['id'];
    $vals["comefrom"] = (($row['comefrom']==null||$row['comefrom']==-1)?-1:$row['comefrom']);    
    $vals["comefrom_url"] = $row['comefromurl'];
    $vals["posttime"] = $row['created_at'];
    $valss = array();
    foreach($vals as $k=>$v){
        array_push($valss,$k.'=\''.addslashes(trim($v)).'\'');
    }

    //事务开始
    $db->query("BEGIN");
    try{
        //插入到车主表
        $sql1 = "INSERT `au_car_owner` SET ".implode(',', $valss);
        $rs1 = $db->query($sql1);
        //echo $row['name'].' '.$row['phone']."已插入到au_car_owner表\n";
        $insert_id = $db->insertId();

        //插入关联信息
        $sql2 = "INSERT `au_car_owner_co_relation` SET owner_id='".$insert_id."',owner_co_id='".$row['owner_co_id']."'";
        //echo "插入".$row['name'].' '.$row['phone']."关联信息\n";
        //echo $sql2."\n";
        $rs2 = $db->query($sql2);

        //更新入库标识
        $sql3 = "UPDATE `au_car_owner_co` SET imported=1 WHERE owner_co_id='".$row['owner_co_id']."'";
        //echo "更新".$row['name'].' '.$row['phone']."原表导入状态为为已导入\n";
        $rs3 = $db->query($sql3);

        if($rs1===false || $rs2===false || $rs3===false){
            //事务回滚
            $db->query("ROLLBACK");
            if($rs1===false){
                echo 'Failed:',$sql1,"\n";
            }elseif($rs2===false){
                echo 'Failed:',$sql2,"\n";
            }elseif($rs3===false){
                echo 'Failed:',$sql3,"\n";
            }
        }else{
            //事务提交
            $db->query("COMMIT");
            //echo $row['owner_co_id']." ".$insert_id." ".date("Y-m-d H:i:s"),"\n";
        }

    }catch(\Exception $e){
        //事务回滚
        $db->query("ROLLBACK");
        echo "发生异常：".$e->getMessage()."\n";
    }


}
